#include <iostream>
#include <cstring>
#include <string>
#include <string.h>

#include <sys/socket.h>
#include <sys/types.h>
#include <sys/signal.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <vector>

#include "my_utils.h"

int initServer(in_addr_t addr, uint16_t port)
{
    int server_sock;
    struct sockaddr_in server_addr; // 使用结构体 SOCKADDR_IN 存储配置
    server_sock = socket(AF_INET, SOCK_STREAM, 0);

    memset(&server_addr, 0, sizeof(server_addr)); // 清零
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = addr; // server端ip地址
    server_addr.sin_port = port;        // 监听端口

    int res = bind(server_sock, (struct sockaddr *)&server_addr, sizeof(server_addr));

    if (res < 0)
    {
        return -1;
    }
    return server_sock;
}

std::vector<int> clean_vector(std::vector<int> list)
{
    std::vector<int> result;
    for (size_t i = 0; i < list.size(); i++)
    {
        if (list[i] == 0)
        {
            continue;
        }
        result.push_back(list[i]);
    }
    return result;
}

int main()
{
    // 初始化socket服务端
    uint16_t port = htons(9000);
    in_addr_t addr = inet_addr("127.0.0.1");

    int server = initServer(addr, port);
    std::vector<int> client_sock;

    // 声明客户端变量
    struct sockaddr_in client_addr;
    socklen_t client_addr_len = sizeof(client_addr);

    // 监听连接
    if (listen(server, 10) < 0)
    {
        std::cout << "server listen error" << std::endl;
        close(server);
        return 0;
    }

    // 将server添加到监听队列
    int max_fd = server;
    fd_set readfds, listenfds;
    FD_ZERO(&readfds);
    FD_SET(server, &readfds);

    unsigned char buffer[1024];

    while (true)
    {
        // 监听连接
        listenfds = readfds;
        int result = select(max_fd + 1, &listenfds, (fd_set *)0, (fd_set *)0, (struct timeval *)0);

        if (result < 1)
        {
            std::cerr << "something error" << std::endl;
            sleep(1);
            continue;
        }

        // 处理新客户端连接请求
        if (FD_ISSET(server, &listenfds))
        {
            int new_sock = accept(server, (struct sockaddr *)&client_addr, &client_addr_len);
            if (new_sock < 0)
            {
                std::cout << "client refuse connection" << std::endl;
                sleep(1);
                continue;
            }

            FD_SET(new_sock, &readfds);
            max_fd = std::max(max_fd, new_sock);
            client_sock.push_back(new_sock);
            std::cout << "adding client on fd " << new_sock << ",ip is:" << inet_ntoa(client_addr.sin_addr) << std::endl;
        }

        // 处理现有客户端数据请求
        for (size_t i = 0; i < client_sock.size(); i++)
        {
            if (FD_ISSET(client_sock[i], &listenfds))
            {
                // 获取请求数据
                int read_size = recv(client_sock[i], buffer, sizeof(buffer), 0);
                if (read_size <= 0)
                {
                    // 如果read_size小于0,说明出现了错误，此时应该关闭连接重新等待连接
                    // 如果错误为EINTR是由中断引起的
                    // 如果是ECONNREST表示网络连接出了问题
                    close(client_sock[i]);
                    FD_CLR(client_sock[i], &readfds);
                    client_sock[i] = 0;
                    std::cerr << "client close connection" << std::endl;
                    continue;
                }
                std::cout << "accpet client " << client_sock[i] << " : " << byte2String(buffer, 0, read_size) << std::endl;

                // 发送数据
                std::vector<unsigned char> request = string2Bytes("x=0,y=0,a=0,");
                unsigned char send_buf[request.size()];
                std::copy(request.begin(), request.end(), send_buf);
                send(client_sock[i], send_buf, request.size(), 0);
            }
        }

        client_sock = clean_vector(client_sock);
    }

    // 关闭连接
    for (size_t i = 0; i < client_sock.size(); i++)
    {
        close(client_sock[i]);
    }

    close(server);
}